package com.health.mapp.utils;

import java.io.BufferedInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;

import org.apache.log4j.Logger;
 
public class GetRemoteFileHTTPClient {
	private static Logger logger = Logger.getLogger(GetRemoteFileHTTPClient.class);
	public GetRemoteFileHTTPClient() {
	}

	/**
	 * // 确定文件是否已经下载，但没有下载完成
	 * */
	private static boolean FileExist(String pathAndFile) 
	{
		File file = new File(pathAndFile);
		if (file.exists())
			return true;
		else
			return false;
	}
	
	/**
	 * // 确定已经下载了的文件大小
	 */
	
 
	private static long FileSize(String pathAndFile) 
	{
		File file = new File(pathAndFile);
		return file.length();
	}

	private static void FileRename(String fName, String nName) 
	{
		 
		File oldfile = new File(fName);
		File newfile = new File(nName);
		oldfile.renameTo(newfile);
		oldfile.delete();
		
	}

	public static void getFile(String urlStr, String filePath) {
		URL url = null;
		HttpURLConnection urlc = null;
		DataOutputStream dos = null;
		BufferedInputStream bis = null;
		FileOutputStream fos = null;
		String localFile = filePath; // 文件保存的地方及文件名，具体情况可以改
		String localFile_bak = filePath + ".temp"; // 未下载完文件加.temp扩展名，以便于区别
		 
		long fileSize = 0;
		long start = System.currentTimeMillis();
		int len = 0;
		byte[] bt = new byte[1024];
	
		RandomAccessFile raFile = null;
		long totalSize = 0; // 要下载的文件总大小
		try {
			url = new URL(urlStr);
			urlc = (HttpURLConnection) url.openConnection();
			totalSize = Long.parseLong(urlc.getHeaderField("Content-Length"));
			logger.debug("The download file size : " + totalSize);
			urlc.disconnect(); // 先断开，下面再连接，否则下面会报已经连接的错误
			urlc = (HttpURLConnection) url.openConnection();
			// 确定文件是否存在
			if (FileExist(localFile_bak)) // 采用断点续传，这里的依据是看下载文件是否在本地有.temp有扩展名同名文件
			{
				logger.debug("File continuingly transmission begin.");
				fileSize = (totalSize-FileSize(localFile_bak))==0?0:FileSize(localFile_bak); // 取得文件在小，以便确定随机写入的位置
				logger.debug("Left FileSize: " + fileSize);
				//HTTP response code: 416是由于读取文件时设置的Range有误造成的，具体的说就是下面这行代码有误：
				//httpConnection.setRequestProperty("RANGE", "bytes=1024-");
				//这个RANGE显然不能超出文件的size
				
				urlc.setRequestProperty("RANGE", "bytes=" + fileSize + "-");

				urlc.setRequestProperty("Accept",
						"image/gif,image/x-xbitmap,image/jpeg,*/*");
				raFile = new RandomAccessFile(localFile_bak, "rw"); // 随机方位读取
				raFile.seek(fileSize); // 定位指针到fileSize位置
				bis = new BufferedInputStream(urlc.getInputStream());
				while ((len = bis.read(bt)) > 0) // 循环获取文件
				{
					raFile.write(bt, 0, len);

				}
				logger.debug(" File continuingly transmission finish. ");
			} 
			else // 采用原始下载
			{
				fos = new FileOutputStream(localFile_bak); // 没有下载完毕就将文件的扩展名命名.bak
				dos = new DataOutputStream(fos);
				bis = new BufferedInputStream(urlc.getInputStream());
				 
				logger.debug("File   transmission begin.");
				while ((len = bis.read(bt)) > 0) // 循环获取文件
				{
					dos.write(bt, 0, len);

				}
				logger.debug("File   transmission finish.");
			}
			logger.debug( "Total cost: " + (System.currentTimeMillis() - start)	/ 1000+" Millis");
		
			//System.out.println(localFile_bak + FileSize(localFile_bak));
			
			

			if (bis != null)
			
				bis.close();
			
			if (dos != null)
				dos.close();
			if (fos != null)
				fos.close();
			if (raFile != null)
				raFile.close();
			// 下载完毕后，将文件重命名
			if (FileSize(localFile_bak) == totalSize) 
			{
				
				FileRename(localFile_bak, localFile);
				 
			}
			
		} catch (Exception e) {
			try {
				if (bis != null)
					bis.close();
				if (dos != null)
					dos.close();
				if (fos != null)
					fos.close();
				if (raFile != null)
					raFile.close();
			} catch (IOException f) {
				f.printStackTrace();
			}
			e.printStackTrace();
		}
		 
				 
		 
		 
	}
	
	public static void main(String[] args)
	{
		
		getFile("","F:/DD.jpeg");
		//System.exit(0);
	}
	
	
}
